#pragma once
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <cstdlib>
#include "Log.hpp"
extern Log lg;
enum
{
    SOCKET_ERR = 2,
    BIND_ERR,
    LISTEN_ERR,

};
class Sock
{
public:
    Sock() : sockfd_(-1)
    {
    }

public:
    void Socket()
    {
        sockfd_ = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd_ < 0)
        {
            lg(Fatal, "socket err, err: %d, errstring: %s", errno, strerror(errno));
            exit(SOCKET_ERR);
        }
        
        int opt = 1;
        setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    }

    void Bind(uint16_t port)
    {
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_addr.s_addr = INADDR_ANY;
        peer.sin_port = htons(port);
        
        if(bind(sockfd_, (sockaddr *)&peer, sizeof(peer)) < 0)
        {
            lg(Fatal, "bind err, err: %d, errstring: %s", errno, strerror(errno));
            exit(BIND_ERR);
        }
    }

    void Listen()
    {
        if(listen(sockfd_, 10) < 0)
        {
            lg(Fatal, "listen err, err: %d, errstring: %s", errno, strerror(errno));
            exit(LISTEN_ERR);
        }
    }


    int Accept(std::string *ip, uint16_t *port)
    {
        sockaddr_in client;
        socklen_t len = sizeof(client);
        int fd = accept(sockfd_, (sockaddr *)&client, &len);
        if(fd < 0)
        {
            lg(Warning, "accept err, err: %d, errstring: %s", errno, strerror(errno));
            return -1;
        }
        else
        {
            char clientip[32];
            inet_ntop(AF_INET, &(client.sin_addr), clientip, sizeof(clientip));
            *ip = clientip;
            *port = ntohs(client.sin_port);
            return fd;
        }
    }

    bool Connect(const std::string &ip, const uint16_t &port)
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        inet_pton(AF_INET, ip.c_str(), &(server.sin_addr));
        server.sin_port = htons(port);

        if(connect(sockfd_, (sockaddr *)&server, sizeof(server)) < 0)
        {
            std::cerr << "connect to " << ip << ":" << port << " error" << std::endl;
            return false;
        }

        return true;
    }

    void Close()
    {
        close(sockfd_);
    }
    
    int Fd()
    {
        return sockfd_;
    }

private:
    int sockfd_;
};